package com.ruoyi.web.controller.module.platform;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Arrays;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OkHttpClientUtil;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.module.wx.UrlScheme;
import com.ruoyi.system.service.module.wx.IWxTemplateService;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.module.platform.IUrlSchemeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 获取 scheme 码Controller
 *
 * @author ruoyi
 * @date 2022-11-17
 */
@Validated
@Api(value = "获取 scheme 码控制器", tags = {"获取 scheme 码管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/scheme")
public class UrlSchemeController extends BaseController {

    private final IUrlSchemeService urlSchemeService;
    private final IWxTemplateService wxTemplateService;

    /**
     * 查询获取 scheme 码列表
     */
    @ApiOperation("查询获取 scheme 码列表")
    @PreAuthorize("@ss.hasPermi('module:scheme:list')")
    @GetMapping("/list")
    public TableDataInfo<UrlScheme> list(@Validated UrlScheme urlScheme) {
        QueryWrapper<UrlScheme> qw = new QueryWrapper<>();

        TableDataInfo<UrlScheme> td = PageUtils.buildDataInfo(urlSchemeService.page(PageUtils.buildPage(),qw));
        List<UrlScheme> list = td.getRows();
        return td;
    }

    /**
     * 导出获取 scheme 码列表
     */
    @ApiOperation("导出获取 scheme 码列表")
    @PreAuthorize("@ss.hasPermi('module:scheme:export')")
    @Log(title = "获取 scheme 码", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<UrlScheme> export(@Validated UrlScheme urlScheme) {
        List<UrlScheme> list = urlSchemeService.list();
        ExcelUtil<UrlScheme> util = new ExcelUtil<UrlScheme>(UrlScheme.class);
        return util.exportExcel(list, "获取 scheme 码");
    }

    /**
     * 获取获取 scheme 码详细信息
     */
    @ApiOperation("获取获取 scheme 码详细信息")
    @PreAuthorize("@ss.hasPermi('module:scheme:query')")
    @GetMapping("/{id}")
    public AjaxResult<UrlScheme> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        UrlScheme urlScheme = urlSchemeService.getById(id);
        return AjaxResult.success(urlScheme);
    }

    /**
     * 新增获取 scheme 码
     */
    @ApiOperation("新增获取 scheme 码")
    @PreAuthorize("@ss.hasPermi('module:scheme:add')")
    @Log(title = "获取 scheme 码", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody UrlScheme urlScheme) {
        return toAjax(urlSchemeService.save(urlScheme) ? 1 : 0);
    }

    /**
     * 修改获取 scheme 码
     */
    @ApiOperation("修改获取 scheme 码")
    @PreAuthorize("@ss.hasPermi('module:scheme:edit')")
    @Log(title = "获取 scheme 码", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody UrlScheme urlScheme) {
        return toAjax(urlSchemeService.updateById(urlScheme) ? 1 : 0);
    }


    /**
     * 修改获取 scheme 码
     */
    @ApiOperation("修改获取 scheme 码")
    @PreAuthorize("@ss.hasPermi('module:scheme:edit')")
    @Log(title = "获取 scheme 码", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PostMapping("/settingScheme")
    public AjaxResult<JSONObject> settingScheme(@RequestBody UrlScheme urlScheme) {
        String token = wxTemplateService.getAccessToken(1);
        String url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=" + token;

        JSONObject jsonObject = new JSONObject();
        String param = " {\n" +
                "            \"jump_wxa\":" +
                "            {" +
                "                \"path\": \""+urlScheme.getWxMiniPath()+"\"," +
                "                    \"query\": \""+urlScheme.getWxMiniQuery()+"\"" +
                "            }," +
                "            \"is_expire\":"+ (urlScheme.getIsExpire() == 1)  +"\n";
                if(urlScheme.getIsExpire() == 1){
                    param += ",\"expire_time\":" + DateUtils.getAfterSecondsByOld(new Date(), urlScheme.getExpireDay() * 3600 ).getTime() + "";
                }
        param += "        }";
        try {
            System.out.println("获取 Scheme 请求" + param);
            String response = OkHttpClientUtil.getInstance().postJson(url,param);
            System.out.println("获取 Scheme 响应" + response);
            jsonObject = JSONUtil.parseObj(response);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return AjaxResult.success(jsonObject);
    }

    /**
     * 删除获取 scheme 码
     */
    @ApiOperation("删除获取 scheme 码")
    @PreAuthorize("@ss.hasPermi('module:scheme:remove')")
    @Log(title = "获取 scheme 码" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return toAjax(urlSchemeService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
